var dbConfig = require('../util/dbconfig')
//测试
getPostCate = (req, res) => {
    let { id } = req.query;
    var sql = `select * from post where casa_id=?`
    var sqlArr = [id];
    var calllBack = (err, data) => {
        if (err) {
            console.log('连接出错');
        } else {
            res.send({
                'list': data
            })
        }
    }
    dbConfig.sqlConnect(sql, sqlArr, calllBack)
}

let getUserInfo = (username) => {  //获取用户详情
    let sql = `select * from userinfo where username=?`;
    let sqlArr = [username];
    return dbConfig.SySqlConnect(sql, sqlArr);
}
//学生登录
getLogin = (req, res) => {
    let { username, password } = req.body;
    let sql = `select * from user where username=? and password=?`;
    let sqlArr = [username, password];
    let callBack = async (err, data) => {
        if (err) {
            console.log(err);
            res.send({
                code: 400,
                msg: '出错了'
            });
        } else if (data == '') {
            res.send({
                code: 400,
                msg: '用户名或者密码出错！'
            });
        } else {
            let result = await getUserInfo(username);
            data[0].userinfo = result[0];
            res.send({
                code: 200,
                msg: '登录成功',
                data: data[0]
            });
        }
    }
    dbConfig.sqlConnect(sql, sqlArr, callBack);

}
//教师登录async
getTeacherLogin = (req, res) => {
    let { username, password } = req.body;
    let sql = `select * from teacherUser where username=? and password=?`;
    let sqlArr = [username, password];
    let callBack = async (err, data) => {
        if (err) {
            console.log(err);
            res.send({
                code: 400,
                msg: '出错了'
            });
        } else if (data == '') {
            res.send({
                code: 400,
                msg: '用户名或者密码出错！'
            });
        } else {
            let user_id = data[0].id;
            // let result = await getUserInfo(user_id);  //教师用户username无法在学生信息表里查到
            // data[0].userinfo = result[0];
            res.send({
                code: 200,
                msg: '登录成功',
                data: data[0]
            });
        }
    }
    dbConfig.sqlConnect(sql, sqlArr, callBack);

}
//登出
logout = (req, res) => {

    res.send({
        code: 200,
        msg: '退出登录'
    })
}
//获取用户信息
let getUser = (username) => {
    let sql = `select * from user where id=? or phone=? or username=?`;
    let sqlArr = [username, username, username];
    return dbConfig.SySqlConnect(sql, sqlArr);
}
//创建副表
let createUserInfo = (user_id) => {
    let sql = `insert into userinfo(user_id,age,sex,job) values(?,?,?,?)`;
    let sqlArr = [user_id, 18, 2, '未设置'];
    return dbConfig.SySqlConnect(sql, sqlArr);
}
//查询学生用户名是否存在
let findUsername = (username) => {
    let sql = `select * from user where username=?`;
    let sqlArr = [username];
    return dbConfig.SySqlConnect(sql, sqlArr);

}
//查询学生用户名是否存在
let findTearcherUsername = (username) => {
    let sql = `select * from teacherUser where username=?`;
    let sqlArr = [username];
    return dbConfig.SySqlConnect(sql, sqlArr);

}
//学生用户注册
register = (req, res) => {
    let { username, password, nickname, repassword } = req.body
    console.log(password, repassword);
    findUsername(username).then(r => {
        if (r.length > 0) {
            res.send({
                code: 400,
                msg: '用户名相同'
            })
        } else {
            if (!username) {
                res.send({
                    code: 400,
                    msg: '请输入用户名'
                })
                return
            } else if (password != repassword) {
                res.send({
                    code: 400,
                    msg: '两次输入密码不同'
                })
                return
            } else if (!nickname) {
                res.send({
                    code: 400,
                    msg: '请输入真实姓名'
                })
                return
            } else {
                let sql = `insert into user(username,password,nickname) value(?,?,?)`;
                let sqlArr = [username, password, nickname];
                let callBack = async (err, data) => {
                    if (err) {
                        console.log(err);
                        res.send({
                            code: 400,
                            msg: '注册失败'
                        });
                    } else {
                        res.send({
                            code: 200,
                            msg: '注册成功',
                            data: data[0],
                        });
                    }
                }
                dbConfig.sqlConnect(sql, sqlArr, callBack);
            }

        }
    })

}
//教师用户注册
TeacherRegister = (req, res) => {
    let { username, password, nickname, repassword } = req.body

    let create_time = new Date()

    findTearcherUsername(username).then(r => {
        if (r.length > 0) {
            res.send({
                code: 400,
                msg: '用户名相同'
            })
        } else {
            if (!username) {
                res.json({
                    code: 400,
                    msg: '请输入用户名',
                    data: '1111'
                })
                return
            } else if (password != repassword) {
                res.send({
                    code: 400,
                    msg: '两次输入密码不同'
                })
                return
            } else if (!nickname) {
                res.send({
                    code: 400,
                    msg: '请输入真实姓名'
                })
                return
            } else {
                let sql = `insert into teacherUser(username,password,nickname,create_time) value(?,?,?,?)`;
                let sqlArr = [username, password, nickname, create_time];
                let callBack = async (err, data) => {
                    if (err) {
                        console.log(err);
                        res.send({
                            code: 400,
                            msg: '注册失败'
                        });
                    } else {
                        res.send({
                            code: 200,
                            msg: '注册成功',
                            data: data[0],
                        });
                    }
                }
                dbConfig.sqlConnect(sql, sqlArr, callBack);
            }

        }
    })

}
//添加课表
addClassTime = (req, res) => {
    let { class_time, kecheng, address } = req.body
    if (!class_time || !kecheng || !address) {
        res.send({
            code: 400,
            msg: '请填写时间、课程、地址！'
        });
    } else {
        let sql = `insert into timeClass(class_time,kecheng,address) value(?,?,?)`;
        let sqlArr = [class_time, kecheng, address];
        let callBack = async (err, data) => {
            if (err) {
                console.log(err);
                res.send({
                    code: 400,
                    msg: '添加失败'
                });
            } else {
                res.send({
                    code: 200,
                    msg: '添加成功'
                });
            }
        }
        dbConfig.sqlConnect(sql, sqlArr, callBack);
    }

}
//删除课表
delClassTime = (req, res) => {
    let { id } = req.body
    if (id) {
        let sql = `delete from timeClass where id = ?`
        let sqlArr = [id]
        let callBack = async (err, data) => {
            if (err) {
                console.log(err);
                res.send({
                    code: 400,
                    msg: '删除失败'
                });
            } else {
                res.send({
                    code: 200,
                    msg: '删除成功'
                });
            }
        }
        dbConfig.sqlConnect(sql, sqlArr, callBack);
    } else {
        res.send({
            code: 400,
            msg: '删除失败'
        });
    }
}
//时间戳转yy mm dd hh mm ss 
let timestampToTime = (timestamp, Yes) => { //时间戳转yy-mm-dd 00 00 00
    let date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
    let Y = date.getFullYear() + '-';
    let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    let D = date.getDate() + ' ';
    let h = date.getHours() + ':';
    let m = date.getMinutes() + ':';
    let s = date.getSeconds();
    // let time = '00:00:00'
    if (Yes) {
        return Y + M + D + h + m + s
    } else {
        return h + m + s;
    }



}
//获取课表
getTimeClass = (req, res) => {
    let { start_time, end_time } = req.body

    let sql = `SELECT * FROM timeClass WHERE class_time BETWEEN ${start_time} and ${end_time}`
    if (!start_time && !end_time) {
        sql = `SELECT * FROM timeClass`
    }

    dbConfig.query(sql).then(data => {
        let dm = 86400000
        let result = [
            [],
            [],
            [],
            [],
            [],
            [],
            []
        ]
        start_time = parseInt(start_time)
        data.map(item => {
            if (item.class_time <= start_time + dm) {
                item.class_time = timestampToTime(item.class_time)
                result[0].push(item)
            } else if (item.class_time <= start_time + dm * 2) {
                item.class_time = timestampToTime(item.class_time)
                result[1].push(item)
            } else if (item.class_time <= start_time + dm * 3) {
                item.class_time = timestampToTime(item.class_time)
                result[2].push(item)
            } else if (item.class_time <= start_time + dm * 4) {
                item.class_time = timestampToTime(item.class_time)
                result[3].push(item)
            } else if (item.class_time <= start_time + dm * 5) {
                item.class_time = timestampToTime(item.class_time)
                result[4].push(item)
            } else if (item.class_time <= start_time + dm * 6) {
                item.class_time = timestampToTime(item.class_time)
                result[5].push(item)
            } else {
                item.class_time = timestampToTime(item.class_time)
                result[6].push(item)
            } 
        })
        if (!start_time && !end_time) {
            result = data
        }
        res.send({
            code: 200,
            msg: '获取成功',
            data: result,
            data2:data
        });
    }).catch(err => {
        console.log(err);
    })

}
//新增考试题
addTestTitle = (req, res) => {
    let { title, itemA, itemB, itemC, itemD, answer } = req.body
    if (title && itemA && itemB && itemC && itemD && answer) {
        let sql = `insert into test(title, itemA, itemB, itemC, itemD, answer) value(?,?,?,?,?,?)`;
        let sqlArr = [title, itemA, itemB, itemC, itemD, answer];
        let callBack = async (err, data) => {
            if (err) {
                console.log(err);
                res.send({
                    code: 400,
                    msg: '添加失败'
                });
            } else {
                res.send({
                    code: 200,
                    msg: '添加成功'
                });
            }
        }
        dbConfig.sqlConnect(sql, sqlArr, callBack);
    } else {
        res.send({
            code: 400,
            msg: '添加失败,请填写所有'
        });
    }
}
//删除考试题
delTestTitle = (req, res) => {
    let { id } = req.query
    if (id) {
        let sql = `delete from test where id = ?`
        let sqlArr = [id]
        let callBack = async (err, data) => {
            if (err) {
                console.log(err);
                res.send({
                    code: 400,
                    msg: '删除失败'
                });
            } else {
                res.send({
                    code: 200,
                    msg: '删除成功'
                });
            }
        }
        dbConfig.sqlConnect(sql, sqlArr, callBack);
    } else {
        res.send({
            code: 400,
            msg: '删除失败'
        });
    }
}
//遍历返回考试数据
let changeTestData = (data, arr) => {
    let newArr = []
    data.map((item, i) => {
        console.log(arr.indexOf(item.id), arr);
        if (arr.indexOf(item.id.toString()) != -1) {
            let itemData = {
                title: item.title,
                id: item.id,
                answer: item.answer,
                type: 0,
                userAnswer: '',
                answerList: [{
                    value: 'A',
                    label: `A.${item.itemA}`
                }, {
                    value: 'B',
                    label: `B.${item.itemB}`
                }, {
                    value: 'C',
                    label: `C.${item.itemC}`
                }, {
                    value: 'D',
                    label: `D.${item.itemD}`
                }],
                example: ''
            }
            newArr.push(itemData)
        }
    })
    // console.log(newArr);
    return newArr

}
//获取考试题
getTestTitle = (req, res) => {
    let { idArr } = req.query || req.body
    console.log(idArr);
    if (idArr) {
        let arr = idArr.split(",")
        let sql = `SELECT * FROM test`
        dbConfig.query(sql).then(data => {
            let result = changeTestData(data, arr)
            res.send({
                code: 200,
                msg: '获取成功',
                data: result,
            });
        }).catch(err => {
            console.log(err);
        })

    } else {
        console.log('111');
        let sql = `SELECT * FROM test`
        dbConfig.query(sql).then(data => {
            // let result = changeTestData(data,'')
            res.send({
                code: 200,
                msg: '获取成功',
                // data: result,
                data2: data
            });
        }).catch(err => {
            console.log(err);
        })
    }


}
//获取签到详情
getSignDetail = (req, res) => {
    let { username } = req.query
    if (username) {
        let sql = `select * from sign where username=?`;
        let sqlArr = [username];
        dbConfig.SySqlConnect(sql, sqlArr).then(e => {
            res.send({
                code: 200,
                msg: '获取成功',
                data: e
            })
        }).catch(err => {
            res.send({
                code: 400,
                msg: '获取失败',
                data: e
            })
            console.log(err);
        })


    } else {
        let sql = `SELECT * FROM sign`
        dbConfig.query(sql).then(data => {
            res.send({
                code: 200,
                msg: '获取成功',
                data: data
            });
        }).catch(err => {
            res.send({
                code: 400,
                msg: '获取失败',
                data: e
            })
            console.log(err);
        })
    }
}
//新增签到
addSign = (req, res) => {
    let { username, nickname, signtime, isSign } = req.body
    if (username && nickname && signtime) {
        let sql = `insert into sign(username, nickname, signtime) value(?,?,?)`;
        let sqlArr = [username, nickname, signtime];
        let callBack = async (err, data) => {
            if (err) {
                console.log(err);
                res.send({
                    code: 400,
                    msg: '签到失败'
                });
            } else {
                let sql1 = `UPDATE user SET  status=1 WHERE username='${username}'`
                dbConfig.query(sql1).then(data => {
                    res.send({
                        code: 200,
                        msg: '签到成功'
                    });
                }).catch(err => {
                    res.send({
                        code: 400,
                        msg: '签到失败'
                    });
                    console.log(err);
                })

            }
        }
        dbConfig.sqlConnect(sql, sqlArr, callBack);
        if (isSign) {
            let sql = `UPDATE user SET  isSign='${isSign}' WHERE username='${username}'`
            dbConfig.query(sql).then(data => {
                // res.send({
                //     code: 200,
                //     msg: '更新成功，请重新登录',
                //     data: data
                // });

            }).catch(err => {
                console.log(err);
            })
        }
    } else {
        res.send({
            code: 400,
            msg: '添加失败,请填写所有'
        });
    }
}
//添加学生成绩
addGrade = (req, res) => {
    let { username, subject, grade, nickname } = req.body
    if (username && subject && grade) {
        let sql = `insert into achievement(username,subject,grade,nickname) value(?,?,?,?)`;
        let sqlArr = [username, subject, grade, nickname];
        let callBack = async (err, data) => {
            if (err) {
                console.log(err);
                res.send({
                    code: 400,
                    msg: '添加失败'
                });
            } else {
                res.send({
                    code: 200,
                    msg: '添加成功'
                });
            }
        }
        dbConfig.sqlConnect(sql, sqlArr, callBack);
    } else {
        res.send({
            code: 400,
            msg: '添加失败,请填写所有'
        });
    }
}
//获取学生成绩
getGrade = (req, res) => {
    let { username } = req.query
    if (username) {
        let sql = `select * from achievement where username=?`;
        let sqlArr = [username];
        dbConfig.SySqlConnect(sql, sqlArr).then(e => {
            res.send({
                code: 200,
                msg: '获取成功',
                data: e
            })
        }).catch(err => {
            res.send({
                code: 400,
                msg: '获取失败',
                data: e
            })
            console.log(err);
        })


    } else {
        let sql = `SELECT * FROM achievement`
        dbConfig.query(sql).then(data => {
            res.send({
                code: 200,
                msg: '获取成功',
                data: data
            });
        }).catch(err => {
            res.send({
                code: 400,
                msg: '获取失败',
                data: data
            })
            console.log(err);
        })
    }
}
getAllUser = (req, res) => {
    let sql = `SELECT * FROM user`
    dbConfig.query(sql).then(data => {
        res.send({
            code: 200,
            msg: '获取成功',
            data: data
        });

    }).catch(err => {
        res.send({
            code: 400,
            msg: '获取失败',
            data: data
        })
        console.log(err);
    })
}
//删除学生成绩
delGrade = (req, res) => {
    let { id } = req.body
    if (id) {
        let sql = `delete from achievement where id = ?`
        let sqlArr = [id]
        let callBack = async (err, data) => {
            if (err) {
                console.log(err);
                res.send({
                    code: 400,
                    msg: '删除失败'
                });
            } else {
                res.send({
                    code: 200,
                    msg: '删除成功'
                });
            }
        }
        dbConfig.sqlConnect(sql, sqlArr, callBack);
    } else {
        res.send({
            code: 400,
            msg: '删除失败'
        });
    }

}
//用户更新个人信息
updateUserInfo = (req, res) => {
    let { username, nickname, region, date, description, sex } = req.body
    let sql = `select * from userinfo where username=?`
    let sqlArr = [username];
    dbConfig.SySqlConnect(sql, sqlArr).then(data => {
        if (data.length == 1) {
            let sql = `UPDATE userinfo SET  nickname='${nickname}',region='${region}',date='${date}',description='${description}',sex='${sex}' WHERE username='${username}'`
            dbConfig.query(sql).then(data => {
                res.send({
                    code: 200,
                    msg: '更新成功，请重新登录',
                    data: data
                });
            }).catch(err => {
                console.log(err);
            })
        } else {
            let sql = `insert into userinfo(username,date,nickname,region,description,sex) value(?,?,?,?,?,?)`;
            let sqlArr = [username,date, nickname, region, description, sex];
            let callBack = async (err, data) => {
                if (err) {
                    console.log(err);
                    res.send({
                        code: 400,
                        msg: '修改失败'
                    });
                } else {
                    res.send({
                        code: 200,
                        msg: '修改成功',
                        data: data[0],
                    });
                }
            }
            dbConfig.sqlConnect(sql, sqlArr, callBack);
        }
    }).catch(err => {
        res.send({
            code: 400,
            msg: '获取失败',
        })
        console.log(err);
    })

}
//查询学生是否已提交
let findUserAnswer = (username) => {
    let sql = `select * from useranswer where username=?`;
    let sqlArr = [username];
    return dbConfig.SySqlConnect(sql, sqlArr);

}
//提交考试答案
setAnswer = (req, res) => {
    let { username, answer } = req.query
    let create_time = new Date()
    if (username && answer) {
        findUserAnswer(username).then(r => {
            if (r.length > 0) {
                res.send({
                    code: 400,
                    msg: '你已提交，请勿重复提交'
                });
            } else {
                let sql = `insert into useranswer(username, answer,create_time) value(?,?,?)`;
                let sqlArr = [username, answer, create_time];
                let callBack = async (err, data) => {
                    if (err) {
                        console.log(err);
                        res.send({
                            code: 400,
                            msg: '提交失败'
                        });
                    } else {
                        res.send({
                            code: 200,
                            msg: '提交成功'
                        });
                    }
                }
                dbConfig.sqlConnect(sql, sqlArr, callBack);
            }
        })

    } else {
        res.send({
            code: 400,
            msg: '添加失败,请填写所有'
        });
    }
}
//获取用户提交考试答案
getUserAnswer = (req, res) => {
    let sql = `SELECT * FROM useranswer`
    dbConfig.query(sql).then(data => {
        res.send({
            code: 200,
            msg: '获取成功',
            data: data
        });
    }).catch(err => {
        res.send({
            code: 400,
            msg: '获取失败',
            data: e
        })
        console.log(err);
    })

}
//跟新用户密码  教师  type=tearcher   学生  type=student
updatepwd = (req, res) => {
    console.log(req);
    let { type, username, oldpwd, newpwd } = req.body
    console.log(type);
    if (type == 'teacher') {
        let sql = `UPDATE teacheruser SET  password='${newpwd}' WHERE username='${username}'`
        dbConfig.query(sql).then(data => {
            res.send({
                code: 200,
                msg: '密码修改成功，请重新登录',
                data: data
            });
        }).catch(err => {
            console.log(err);
        })
    } else if (type == 'student') {
        let sql = `UPDATE user SET  password='${newpwd}' WHERE username='${username}'`
        dbConfig.query(sql).then(data => {
            res.send({
                code: 200,
                msg: '密码修改成功，请重新登录',
                data: data
            });
        }).catch(err => {
            console.log(err);
        })
    }
}
//获取所有学生用户
getuser = (req, res) => {
    let { username } = req.query
    if (username) {
        let sql = `select * from user where username=?`;
        let sqlArr = [username];
        dbConfig.SySqlConnect(sql, sqlArr).then(e => {
            res.send({
                code: 200,
                msg: '获取成功',
                data: e
            })
        }).catch(err => {
            res.send({
                code: 400,
                msg: '获取失败',
                data: e
            })
            console.log(err);
        })


    } else {
        let sql = `SELECT * FROM user`
        dbConfig.query(sql).then(data => {
            res.send({
                code: 200,
                msg: '获取成功',
                data: data
            });
        }).catch(err => {
            res.send({
                code: 400,
                msg: '获取失败',
                data: e
            })
            console.log(err);
        })
    }
}
//获取教师评论
getRemark = (req, res) => {
    let { username } = req.query
    if (username) {
        let sql = `select * from remark where username=?`;
        let sqlArr = [username];
        dbConfig.SySqlConnect(sql, sqlArr).then(e => {
            res.send({
                code: 200,
                msg: '获取成功',
                data: e
            })
        }).catch(err => {
            res.send({
                code: 400,
                msg: '获取失败',
                data: e
            })
            console.log(err);
        })


    } else {
        let sql = `SELECT * FROM remark`
        dbConfig.query(sql).then(data => {
            res.send({
                code: 200,
                msg: '获取成功',
                data: data
            });
        }).catch(err => {
            res.send({
                code: 400,
                msg: '获取失败',
                data: e
            })
            console.log(err);
        })
    }
}
//教师设置评论 
setRemark = (req, res) => {
    let { username, remark } = req.body
    let create_time = new Date()
    if (username && remark) {
        let sql = `insert into remark(username,remark,create_time) value(?,?,?)`;
        let sqlArr = [username, remark, create_time];
        let callBack = async (err, data) => {
            if (err) {
                console.log(err);
                res.send({
                    code: 400,
                    msg: '添加失败'
                });
            } else {
                res.send({
                    code: 200,
                    msg: '添加成功'
                });
            }
        }
        dbConfig.sqlConnect(sql, sqlArr, callBack);
    } else {
        res.send({
            code: 400,
            msg: '添加失败,请填写所有'
        });
    }
}
//教师提交考试
submitTest = (req, res) => {
    let { idArr, subject, test_type } = req.body
    console.log(idArr, test_type, subject);
    if (idArr && subject && test_type) {
        let sql = `insert into allkaoshi(idArr,subject,test_type) value(?,?,?)`;
        let sqlArr = [idArr, subject, test_type];
        let callBack = async (err, data) => {
            if (err) {
                console.log(err);
                res.send({
                    code: 400,
                    msg: '添加失败'
                });
            } else {
                res.send({
                    code: 200,
                    msg: '添加成功'
                });
            }
        }
        dbConfig.sqlConnect(sql, sqlArr, callBack);
    } else {
        res.send({
            code: 400,
            msg: '添加失败,请填写所有'
        });
    }
}
//或去所有考试
getAllTest = (req, res) => {
    let sql = `SELECT * FROM allkaoshi`
    dbConfig.query(sql).then(data => {
        res.send({
            code: 200,
            msg: '获取成功',
            data: data
        });
    }).catch(err => {
        res.send({
            code: 400,
            msg: '获取失败',
            data: e
        })
        console.log(err);
    })
}
//教师设置学生用户签到
setUserSign = (req, res) => {
    let { username, status, isSign } = req.body
    let sql = `UPDATE user SET  status='${status}',isSign='${isSign}' WHERE username='${username}'`
    dbConfig.query(sql).then(data => {
        res.send({
            code: 200,
            msg: '设置签到成功',
            data: []
        });
    }).catch(err => {
        res.send({
            code: 400,
            msg: '设置签到失败',
            data: data
        });
        console.log(err);
    })
}
module.exports = {
    getUser,
    getPostCate,
    getLogin,
    logout,
    register,
    getTeacherLogin,
    TeacherRegister,
    addClassTime,
    delClassTime,
    getTimeClass,
    addTestTitle,
    delTestTitle,
    getTestTitle,
    getSignDetail,
    addSign,
    addGrade,
    getGrade,
    delGrade,
    updateUserInfo,
    setAnswer,
    getUserAnswer,
    updatepwd,
    getuser,
    getAllUser,
    getRemark,
    setRemark,
    submitTest,
    setUserSign,
    getAllTest
}